package metar_taf;

import java.io.IOException;
import java.util.TimeZone;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@SuppressWarnings("serial")
public class MetarServlet extends HttpServlet {

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		resp.setHeader("Access-Control-Allow-Origin", "*");
		resp.setCharacterEncoding("UTF-8");
		resp.setContentType("text/plain; charset=UTF-8");
		String icao = req.getParameter("icao");
		String zone = req.getParameter("zone");
		if (icao == null) {
			return;
		}
		if(zone == null) {
			zone = "GMT";
		}
		CachedURLLoader urlLoader = new CachedURLLoader(
				"http://weather.noaa.gov/pub/data/observations/metar/stations/"
						+ icao.toUpperCase() + ".TXT");
		String metarStr = urlLoader.load();
		MetarParser metarParser = new MetarParser();
		resp.getWriter().print(metarParser.parse(metarStr).toJSON(TimeZone.getTimeZone(zone)));
		resp.flushBuffer();
	}

}
